import commonService from "@/api/services/commonService";
import editorStore from "@/editorComponent/editorStore";
import { Button, Space, message } from "antd";
import clsx from "clsx";
import { cloneDeep } from "lodash";
import { autorun, toJS } from "mobx";
import { useEffect, useState } from "react";
import styles from "./index.module.less";
import InputContrl from "./InputContrl/InputContrl";

interface Iprops {
  changeLoading: (loading: boolean) => void;
  closeOpen: () => void;
}

// 加入购物车
export default function JoinShopCar({ changeLoading, closeOpen }: Iprops) {
  const [sizeList, setSizeList] = useState<Array<{ name: string, count: number }>>([]);
  const [totalCount, setTotalCount] = useState<number>(0);

  useEffect(() => autorun(() => {
    const { goodsData } = editorStore;
    if (goodsData) {
      const sizePrice = toJS(goodsData.sizePrice) || [];
      setSizeList(sizePrice.map(({ size }) => ({ name: size, count: 0 })));
      setTotalCount(0);
    }
  }), []);

  //修改数量
  const onChange = (value: number | null, size: string) => {
    if (editorStore.goodsData) {
      let totalCount = 0;
      sizeList.map(s => {
        if (s.name === size) {
          s.count = (value || 0);
        }
        totalCount += s.count;
      });
      setSizeList(cloneDeep(sizeList));
      setTotalCount(totalCount);
    }
  }

  const addShopCar = async () => {
    if (totalCount === 0) {
      return message.info('请选择数量！');
    }
    const id = await editorStore.save();

    const task: Array<Promise<void>> = [];

    sizeList.map(sizeL => {
      if (sizeL.count > 0) {
        task.push(commonService.addCartApi({ num: sizeL.count, size: sizeL.name, fpId: id }));
      }
    });

    await Promise.all(task);

    window.location.href = `/#/admin/cart`;
  }

  return (
    <div className={styles.JoinShopCar}>
      <div className={styles.sizeBox}>
        {
          sizeList.map(({ name, count }, i: number) => (
            <div key={i} className={clsx(styles.sizeItem)}>
              <span className={styles.nameNormalWidth}>{name}</span>
              <InputContrl name={name} count={count} onChange={onChange} />
            </div>
          ))
        }
      </div>
      <div className={styles.yellowBar}>
        <span className={styles.totalCount}>总件数：{totalCount}个</span>
      </div>
      <div className={styles.shopCar}>
        <Space wrap>
          <Button shape="round" size="small" className={styles.cancle} onClick={closeOpen}>取消</Button>
          <Button shape="round" size="small" type="primary" onClick={addShopCar}>确定</Button>
        </Space>
      </div>
    </div>
  );

}